<!-- 防止页面数据重复定义,模板数据统一在此 -->
<!--:
    var statusList = dicttag.getDictList('schedule_status_type');
    var statusJson = commontag.toJson(statusList);
-->
<!-- widget grid -->
<div id="scheduleTable"></div>
<!-- end widget grid -->

<script type="text/javascript">

    /* DO NOT REMOVE : GLOBAL FUNCTIONS!
     *
     * pageSetUp(); WILL CALL THE FOLLOWING FUNCTIONS
     *
     * // activate tooltips
     * $("[rel=tooltip]").tooltip();
     *
     * // activate popovers
     * $("[rel=popover]").popover();
     *
     * // activate popovers with hover states
     * $("[rel=popover-hover]").popover({ trigger: "hover" });
     *
     * // activate inline charts
     * runAllCharts();
     *
     * // setup widgets
     * setup_widgets_desktop();
     *
     * // run form elements
     * runAllForms();
     *
     ********************************
     *
     * pageSetUp() is needed whenever you load a page.
     * It initializes and checks for all basic elements of the page
     * and makes rendering easier.
     *
     */
    pageSetUp();

    /*
     * ALL PAGE RELATED SCRIPTS CAN GO BELOW HERE
     */
    // PAGE RELATED SCRIPTS
    // pagefunction
    var pagefunction = function () {

        var params = {group: "${group}"};
        var $schedule_table = $('#scheduleTable');

        /**
         * 根据类型获取类型label
         * @param value 类型value
         */
        function getLabel(value) {
            var dicts = eval('${statusJson!""}');
            // 设置默认显示type
            var label = value;
            if (dicts) {
                $.each(dicts, function (i, dict) {
                    if (dict['value'] == value) {
                        label = dict['label'];
                        return false;
                    }
                });
            }
            return label;
        }

        var datatable = new DataTableData({
                    databind: $schedule_table.get(0),
                    //数据请求url地址
                    dataurl: '${ctx}/tools/schedule/list',
                    //数据请求参数
                    params: params,
                    hasCache: true,
                    hasCheck: true,
                    config: {"iDisplayLength": 10},
                    info: false,
                    alls: true,
                    checkBind: 'id',
                    toolbarStates: {
                        "add": {
                            show: false
                        },
                        "edit": {
                            action: function () {
                                editJob();
                            }
                        },
                        "delete": {
                            show: false
                        },
                        "refresh": {
                            action: function () {
                                var treeObj = $.fn.zTree.getZTreeObj("scheduleTree");
                                var nodes = treeObj.getSelectedNodes();
                                if (nodes && nodes.length > 0) {
                                    datatable.refresh({group: nodes[0].id});
                                }
                            }
                        }
                    },

                    hasDetails: true,
                    details: function (row, $div) {
                        //覆盖传入模式
                        var suboptions = {
                            //默认table配置项，需要修改则覆盖
                            serverSide: true,
                            //数据请求url地址
                            dataurl: '${ctx}/tools/schedule/historyList',
                            params: {
                                name: row['name'],
                                group: row['group']
                            },
                            searching: false,
                            paging: true,
                            config: {"iDisplayLength": 4},
                            hasCache: false,
                            hasSelect: true,
                            hasIndex: true,
                            info: false,
                            datas: [], //[｛name:'John',position:'china'｝]
                            columns: [],
                            dom: "t" + "<'dt-toolbar-footer'<'col-sm-6 col-xs-12 hidden-xs'i><'col-sm-6 col-xs-12'p>>"
                        };
                        //必须项目
                        //远程模式则按照DataTable配置
                        suboptions.databind = $div.get(0);
                        suboptions.columns = [
                            {data: 'startTime', title: '任务开始时间'},
                            {data: 'finishTime', title: '任务结束时间'},
                            {
                                data: 'duration', title: '任务持续时间',
                                render: function (value) {
                                    return '<div class="text-center"><span class="badge">' + value + 'MS</span></div>';
                                }
                            },
                            {
                                data: 'status', title: '任务结果',
                                render: function (value) {
                                    var res = "异常";
                                    if (value === 0) {
                                        res = "正常";
                                    }
                                    return '<div class="text-center"><span class="badge bg-color-greenLight">' + res + '</span></div>';
                                }
                            },
                            {data: 'cron', title: '执行时间信息'}
                        ];
                        return new DataTableData(suboptions);
                    },

                    // 对于没有记录历史的任务,不显示下拉
                    drawCallback: function (datatable) {
                        datatable.rows().data().each(function (data, index) {

                            if (data['history'] === false) {
                                var $row = $(datatable.rows().nodes()[index]);
                                $row.find('.details-control').removeClass('details-control')
                            }
                        });
                    },

                    toolbarButonsStates: [
                        {key: '#scheduleTable .dt-toolbar .dt_action .dt-pause-btn', state: 1},
                        {key: '#scheduleTable .dt-toolbar .dt_action .dt-resume-btn', state: 1}
                    ],
                    columns: [
                        {
                            data: 'name', title: '名称',
                            render: function (value) {
                                return '<a href="javascript:" onclick="editJob(' + "'" + value + "'" + ')">' + value + '</a>';
                            }
                        },
                        {data: 'group', title: '任务组'},
                        {
                            data: 'jobRuntimeEntity.status', title: '状态', width: '50px',
                            render: function (value) {
                                return '<div class="text-center"><span class="label label-default">' + getLabel(value) + '</span></div>';
                            }
                        },
                        {
                            data: 'cron', title: '类型', width: '70px', defaultContent: '',
                            render: function (value) {
                                var txt = '表达式';
                                if (value == null || value == undefined || value == '') {
                                    txt = '时间间隔';
                                }
                                return '<div class="text-center"><span class="label txt-color-pink">' + txt + '</span></div>';
                            }
                        },
                        {data: 'jobRuntimeEntity.previousFireTime', width: '130px', title: '上次运行时间', defaultContent: ''},
                        {data: 'jobRuntimeEntity.nextFireTime', width: '130px', title: '下次运行时间', defaultContent: ''}
                    ]
                }
        );

        /**
         * 添加暂停和恢复按钮
         */
        function addButton() {
            var dt_action = $schedule_table.find('.dt-toolbar .dt_action');
            // 暂停
            dt_action.append("<span class='margin-left-5'></span>");
            dt_action.append("<a class='btn btn-default dt-pause-btn' rel='tooltip' data-placement='bottom' " +
                    "data-original-title='暂停'><i class='fa fa-pause txt-color-red'></i> Pause</a>");
            dt_action.find('.dt-pause-btn').on('click', function () {
                pause();
            });
            // 恢复
            dt_action.append("<span class='margin-left-5'></span>");
            dt_action.append("<a class='btn btn-success dt-resume-btn' rel='tooltip' data-placement='bottom' " +
                    "data-original-title='恢复'><i class='fa fa-play'></i> Resume</a>");
            dt_action.find('.dt-resume-btn').on('click', function () {
                resume();
            });
        }

        addButton();

        /**
         * 修改任务
         */
        function editJob(ed) {
            var name;
            if (ed != null) {
                name = ed;
            } else {
                var selDatas = datatable.getSelectedDatas();
                if (selDatas && selDatas.length > 0) {
                    name = selDatas[0]['name'];
                }
            }

            var treeObj = $.fn.zTree.getZTreeObj("scheduleTree");
            var node = treeObj.getNodeByParam("id", name);
            if (node) {
                treeObj.selectNode(node);
                $("#" + node.tId + "_a").click();
            }
        }

        /**
         * 暂停按钮点击
         */
        function pause() {
            // 获取当前所有选择列
            var selDatas = datatable.getSelectedDatas();
            if (selDatas && selDatas.length > 0) {
                // send
                ajaxCoomand({
                    url: '${ctx}/tools/schedule/pause',
                    data: {name: selDatas[0]['name'], group: selDatas[0]['group']},
                    callback: function () {
                        datatable.refresh();
                    }
                });
            }
        }

        /**
         * 恢复按钮点击
         */
        function resume() {
            // 获取当前所有选择列
            var selDatas = datatable.getSelectedDatas();
            if (selDatas && selDatas.length > 0) {
                // send
                ajaxCoomand({
                    url: '${ctx}/tools/schedule/resume',
                    data: {name: selDatas[0]['name'], group: selDatas[0]['group']},
                    callback: function () {
                        datatable.refresh();
                    }
                });
            }
        }

        // 注册
        window.editJob = editJob;
        window.pause = pause;
        window.resume = resume;

    };

    // destroy generated instances
    // pagedestroy is called automatically before loading a new page
    // only usable in AJAX version!
    var pagedestroy = function () {
        // 移除注册方法
        window.editJob = undefined;
        window.pause = undefined;
        window.resume = undefined;

    };
    // end destroy

    // load related plugins
    loadScript("/static/js/plugin/datatables/jquery.dataTables.js", function () {
        loadScript("/static/js/plugin/datatables/dataTables.colVis.js", function () {
            loadScript("/static/js/plugin/datatables/dataTables.tableTools.js", function () {
                loadScript("/static/js/plugin/datatables/dataTables.bootstrap.js", function () {
                    loadScript("/static/js/plugin/datatable-responsive/datatables.responsive.js", function () {
                        loadScript("/static/js/extend/DataTableData.js", pagefunction);
                    });
                });
            });
        });
    });

</script>